package org.jerrymouse.jsa4j.db.kv;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 数据库工厂。你可以用它来得到DBManager。需要编写配置文件。<br/>
 * 使用时需要注入xmlPath的值，默认是“META-INF/jsa4j-db-kv.xml“
 * 
 * @author yankai
 * 
 */
public class DBManagerFactory {
	private static Log log = LogFactory.getLog(DBManagerFactory.class);

	public enum DBManagerType {
		DERBY, GAE, MEM, GAEMEM, CASSANDRA
	}

	/**
	 * 默认为：“classpath:META-INF/jsa4j-db-kv.xml“
	 * 
	 */
	private String configPath = "classpath:META-INF/jsa4j-db-kv.xml";

	// private static String DERBY = "derby";
	// private static String GAE = "gae";
	// private static String MEM = "mem";
	// private static String GAEMEM = "gae-mem";
	// private static String CASSABDRA = "cassandra";

	/**
	 * name为你需要的DB的名字，在配置文件中指定
	 * 
	 * @param classpath
	 * @return
	 */
	public DBManager getDBManager(String name) {
		XMLConfig xmlConfig = new XMLConfig(XMLConfig
				.getConfigInputStream(configPath));
		DBManager dbManager = createClassByName(xmlConfig.getProvider(name));
		if (dbManager != null)
			dbManager.setProperties(xmlConfig.getProperties(name));
		return dbManager;
	}

	public DBManager getDBManager(DBManagerType dbManagerEnum) {
		return getDBManager(dbManagerEnum.toString().toLowerCase());
	}

	private DBManager createClassByName(String provider) {
		log.trace(provider);
		DBManager dbManager = null;
		try {
			dbManager = (DBManager) Class.forName(provider).newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			e.printStackTrace();
			return null;
		}
		return dbManager;
	}

	public String getConfigPath() {
		return configPath;
	}

	public void setConfigPath(String configPath) {
		this.configPath = configPath;
	}

}
